<template>
  <div class="h-full flex flex-col">
    <SearchContainer @search="getData" @reset="() => reset()">
      <a-form ref="formRef" class="form-style-flex" :model="formState" :label-col="{ style: { width: '80px' } }">
        <a-form-item name="bqid" label="" class="ml-2">
          <SelectArea
            v-model:value="formState.bqid"
            class="w-48 mr-2"
            use-cache
            set-cache
            post-url
            :post-params="{ wardTypeCodes: ['QYLB001', 'QYLB002'] }"
            @change="getData"
          />
        </a-form-item>
        <a-form-item name="zjm" label="" class="ml-2">
          <a-input v-model:value="formState.zjm" class="w-72" placeholder="姓名/助记码/卡号/手机号/身份证号" allow-clear @keydown.enter="getData" />
        </a-form-item>
      </a-form>
    </SearchContainer>
    <a-card class="flex-1 mt-2">
      <div class="w-full flex justify-between">
        <div class="w-3/12">
          <BaseTable
            fill
            :data-source="tableData"
            :loading="loading"
            row-key="inplsh"
            :row-selection="{
              selectedRowKeys: selectedRowKeys,
              getCheckboxProps: (record) => ({
                disabled: record.status !== 0 || record.chargeStatus !== 0
              }),
              onChange: onSelectChange
            }"
            column-code="000955"
            :pagination="pagination"
          >
            <template #bodyCell="{ column, index }">
              <template v-if="column.dataIndex === 'xh'">
                {{ index + 1 }}
              </template>
            </template>
          </BaseTable>
        </div>
        <div class="w-9/12 ml-2">
          <BaseTable :data-source="dataSource" column-code="000956">
            <template #bodyCell="{ column, index, record }">
              <template v-if="column.dataIndex === 'xh'">
                {{ index + 1 }}
              </template>
              <!-- <template v-if="column.dataIndex === 'advTypeCode'">
                <EditCell>
                  <a-select
                    v-model:value="record.advTypeCode"
                    :disabled="!record.isNew"
                    :virtual="false"
                    :options="options"
                    placeholder="请选择"
                    @change="(data) => onChangeClassify(data, record)"
                  />
                </EditCell>
              </template> -->
              <template v-if="column.dataIndex === 'advName'">
                <!-- 可选项为“项目类别”为治疗、护理、膳食、其他、材料。 -->
                <EditCell>
                  <SelectTable
                    v-model:value="record.advName"
                    :disabled="!record.isNew"
                    type="补记账"
                    :search-params="{ xmlbbh: ['3', '7', '8', '30', '99'] }"
                    :auto-focus="record.isNew && focusCell === record.key + '处置'"
                    @select="(data) => onSelectTable(data, record)"
                  />
                </EditCell>
              </template>
              <template v-if="column.dataIndex === 'count'">
                <EditCell>
                  <BaseInput
                    v-model:value="record.count"
                    v-input:float.3
                    :disabled="!record.isNew"
                    :auto-focus="record.isNew && focusCell === record.key + '数量'"
                    class="text-right"
                    placeholder="请输入"
                    @keydown.enter="addRow()"
                    @blur="editRow(record)"
                  />
                </EditCell>
              </template>
              <div v-if="column.dataIndex === 'amount'">
                <div v-if="record.isNew">{{ formatAmount((record.price || 0) * (record.count || 0)) }}</div>
                <div v-else>{{ formatAmount(record.amount) }}</div>
              </div>
              <div v-if="column.dataIndex === 'memo'">
                <EditCell>
                  <BaseInput v-model:value="record.memo" :disabled="!record.isNew" placeholder="请输入" @blur="editRow(record)" />
                </EditCell>
              </div>
              <template v-if="column.dataIndex === 'action'">
                <a-button danger type="link" size="small" @click="onPrintInventory(record)">删除</a-button>
              </template>
            </template>
            <template #footer>
              <div class="text-center sticky bottom-0">
                <a-button :disabled="selectedRowKeys.length <= 0" class="mr-2" @click="addRow()"> 新增一条 </a-button>
                <a-button :disabled="selectedRowKeys.length <= 0" type="primary" @click="saveNewRows()"> 保存入账 </a-button>
              </div>
            </template>
          </BaseTable>
        </div>
      </div>
    </a-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import { formatAmount } from '@/utils/format.js'
import SearchContainer from '@/components/SearchContainer'

const formRef = ref(null)
const formState = ref({
  bqid: undefined,
  zjm: ''
})
const dataSource = ref([])
const defaultAdvTypeCode = ref('')
const options = ref([])
const selectedRowKeys = ref([])

const { loading, tableData, pagination, getData } = useTable({
  url: '/inp/inpComprehensive/getInpRecordInfo',
  immediate: true,
  params: formState.value,
  formatParams: () => {
    return {
      bqid: formState.value.bqid,
      zjm: formState.value.zjm
    }
  }
})
const saveNewRows = () => {
  const newRow = dataSource.value.filter((item) => item.isNew)
  newRow.forEach((item, index) => {
    if (item.count && item.advName) {
      if (index === newRow.length - 1) fetchSave({ inplshs: selectedRowKeys.value, inpExpensesEntities: newRow })
    } else {
      message.destroy()
      message.error('请填写完整信息')
    }
  })
}
// 保存行
const fetchSave = async (rows) => {
  const { code, msg } = await post('/inp/inpComprehensive/doBatchSaveInpExpenses', rows)
  if (code !== 0) return message.error(msg || '操作失败')
  message.destroy()
  message.success(msg || '保存成功')
  dataSource.value = []
}
//添加行
const addRow = () => {
  const key = `row-${dataSource.value.length}`
  const addRow = {
    key,
    isNew: true,
    advTypeName: '膳食费',
    advTypeCode: defaultAdvTypeCode.value
    // inplshs: selectedRowKeys.value
    // deptCode: props.selectedItem.lastDeptCode,
    // advExecId: selectRow.value.id,
    // accountType: props.formState.accountType
  }
  dataSource.value.push(addRow)
  // focusCell.value = key + '处置'
}

const onSelectChange = (key) => {
  selectedRowKeys.value = key
  dataSource.value = []
}
//分类
// const onChangeClassify = (data, record) => {
//   options.value.forEach((item) => {
//     if (item.value === data) {
//       record.advTypeName = item.label
//     }
//   })
//   record.advName = ''
//   record.advCode = ''
//   record.price = ''
//   record.unit = ''
//   // focusCell.value = record.key + '处置'
// }
const onSelectTable = (medicine, row) => {
  row.advName = medicine.mc
  row.advCode = medicine.bh
  row.price = medicine.dj
  row.unit = medicine.dw || '次'
  // focusCell.value = row.key + '数量'
}
const getProjectList = async () => {
  const { code, data } = await post('/drugStorage/comprehenive/getMedicalProjectList_BJZ')
  if (code !== 0) return
  options.value = data.map((item) => {
    if (item.mc === '膳食费') {
      defaultAdvTypeCode.value = item.bh.toString()
    }
    return {
      label: item.mc,
      value: item.bh.toString()
    }
  })
}
const onPrintInventory = async (row) => {
  const { code, msg, data } = await post('/inp/Print/printAdmissionList', {
    inplsh: row?.inplsh,
    jslb: 'SF',
    dylb: 'ZY'
  })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}
const reset = () => {
  formRef.value.resetFields()
  getData()
}
onMounted(() => {
  getProjectList()
})
</script>
